import {Component, EventEmitter, Output, ElementRef, OnInit, ViewChild} from '@angular/core';
import {WriteInquiryService} from './write-inquiry.service';
import {Util} from "../../../../common/util";
import {Observable} from "rxjs/Observable";
import * as _ from 'lodash';

@Component({
  selector: 'new-stock-purchase-write-inquiry',
  templateUrl: './write-inquiry.component.html',
  styleUrls: ['./write-inquiry.component.scss'],
  providers: [WriteInquiryService]
})
export class WriteInquiryComponent implements OnInit {

  public $ = window["$"];


  public marketNo = {
    "1": "上交所",
    "2": "深交所"
  };

  // 录入询价模态框内数据变量
  public writeInquiryModalData: any = {};

  // 录入询价模态框内下拉变量
  public stockSelectData;

  // 获取的基金下拉列表
  public fundList = [];

  // 未剔除组合数组
  public withoutDeleteList = [];

  // 已剔除组合数组
  public deleteList = [];

  @ViewChild("modal")
  public modal: ElementRef;

  @ViewChild("stockSelect")
  public stockSelect: ElementRef;

  @ViewChild("withoutDeleteListBody")
  public withoutDeleteListBody: ElementRef;

  @ViewChild("deleteListBody")
  public deleteListBody: ElementRef;

  // 关闭事件
  @Output()
  close: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(public WriteInquiryService: WriteInquiryService) {

  }

  ngOnInit() {

  }

  /**
   * 打开模态框
   * 1. 先获取select下拉数据
   * 2. 根据select第一个值来查询询价信息
   * 3. 用查询回来的询价信息来获取基金列表，来做剔除
   */
  public openModal() {
    this.getStockSelectData();
    Util.$(this.modal.nativeElement).modal('show');
  }

  public closeModal(): void {
    this.close.emit(true); // 关闭后触发上层刷新事件
    Util.$(this.modal.nativeElement).modal('hide');
  }

  // 获取询价下拉数据
  public getStockSelectData() {
    const param = {
      dataType: 3,
      page: 0,
      pageSize: 0
    };
    return this.WriteInquiryService.getStockSelectData(param).subscribe(result => {
      if (result.list.length !== 0) {
        this.stockSelectData = result.list;
        // 根据下拉默认值进行查询新股信息
        this.getNewstockInfo(result.list[0].vcNewstockId);
      }
    });
  }

  // 获取询价信息，并且处理剔除组合分别显示的数据
  // @param data 股票代码
  public getNewstockInfo(data) {
    // 初始化模态框询价数据变量
    this.writeInquiryModalData = {};
    this.withoutDeleteList = [];
    this.deleteList = [];

    return this.WriteInquiryService.getNewstockInfo(data).subscribe(result => {
      if (result) {
        this.writeInquiryModalData = result;
        // 金钱转义 TODO 临时解决方案，以后要改
        this.writeInquiryModalData.lIpoStock = this.calculateMoney(result.lIpoStock/10000,'0,0.0000'); // 发行数量
        this.writeInquiryModalData.enMaxBuy = this.calculateMoney(result.enMaxBuy/10000,'0,0.0000'); // 申购数量上限（万股)
        this.writeInquiryModalData.enMinBuy = this.calculateMoney(result.enMinBuy/10000,'0,0.0000'); // 申购数量下限
        this.writeInquiryModalData.lPerNum = this.calculateMoney(result.lPerNum/10000,'0,0.0000'); // 申购最小变动单位（万股）
        this.writeInquiryModalData.enMinivalue = this.calculateMoney(result.enMinivalue/10000,'0,0.0000'); // 日均市值门槛（万元）

        // 百分比转义  TODO 临时解决方案，以后要改
        this.writeInquiryModalData.enPredictRate = this.calculatePercent(this.writeInquiryModalData.enPredictRate); // 预计中签率
        this.writeInquiryModalData.enScaleCoefficient = this.calculatePercent(this.writeInquiryModalData.enScaleCoefficient);// 基金规模系数

        // 获取基金列表
        if (result.lNewstockNo) {
          this.getFundList(result.lNewstockNo);
        }
      }
    });
  }

  /**
   * 对指定文字、数字进行数字格式化
   * @param value 目标源
   * @param format 格式化格式，具体可以查看文档http://numeraljs.com
   * @param positive 是否启用正数 '+' 号表示，默认false，不启用
   * @param emptyStrWhenZero 目标源的值为0时，是否返回空字符串，默认false，不启用
   * @param enableFormatNull 当目标源的值为null时，是否允许进行格式化，默认false，不允许
   * @return 格式化后的数字字符串
   */
  calculateMoney(value: any, format: string = '0,0.00', positive: boolean = false,
             emptyStrWhenZero: boolean = false,enableFormatNull: boolean = false): string {
    if (isNaN(value)){
      return "";
    }
    if (value == null && !enableFormatNull) {
      return "";
    }
    if (emptyStrWhenZero && (parseFloat(value) === 0)) {
      return "";
    }
    return window['numeral'](value).format(positive ? '+' + format : format);
  }

  // 对转义后的金额还原
  reCalculateMoney(data){
    if(data==""){
      return "";
    }
    if(data.charAt(data.length-1) == "." ){
      return data.substring(0, data.length - 1) + '0000';
    }
    if(!(data.includes("."))){
      return data + '0000';
    }
    var arr = _.without(data.split(""),',','.');
    var str = "";
    for (var i =0 ; i < arr.length; i++){
      str += arr[i];
    }
    return str;
  }

  // 百分比转义
  calculatePercent(data){
    if(data){
      return data * 100;
    }
  }


  // 对转义过的百分比还原
  reSetCalculatePercent(data){
    if(data){
      return data / 100;
    }
  }

  // 重设金钱与百分比
  public reSetMoneyAndPercent(){
    this.writeInquiryModalData.lIpoStock = this.reCalculateMoney(this.writeInquiryModalData.lIpoStock); // 发行数量
    this.writeInquiryModalData.enMaxBuy = this.reCalculateMoney(this.writeInquiryModalData.enMaxBuy); // 申购数量上限（万股)
    this.writeInquiryModalData.enMinBuy = this.reCalculateMoney(this.writeInquiryModalData.enMinBuy); // 申购数量下限
    this.writeInquiryModalData.lPerNum = this.reCalculateMoney(this.writeInquiryModalData.lPerNum); // 申购最小变动单位（万股）
    this.writeInquiryModalData.enMinivalue = this.reCalculateMoney(this.writeInquiryModalData.enMinivalue); // 日均市值门槛（万元）
    this.writeInquiryModalData.enPredictRate = this.reSetCalculatePercent(this.writeInquiryModalData.enPredictRate); // 预计中签率
    this.writeInquiryModalData.enScaleCoefficient = this.reSetCalculatePercent(this.writeInquiryModalData.enScaleCoefficient);// 基金规模系数
  }

  // 获取基金列表
  public getFundList(data) {
    const param = {
      type: 1,
      lNewstockNo: data
    };
    return this.WriteInquiryService.getFundList(param).subscribe(result => {
      if (result) {
        this.withoutDeleteList = result;
        _.forEach(this.withoutDeleteList, item => {
          item.isChecked = false;
        });
        this.FilterToGroup(this.writeInquiryModalData.vcFundFilter, this.withoutDeleteList);
      }
    });
  }

  /**
   * 过滤数据，进行剔除或未剔除分类
   * @param {any} fliterData
   * @param {any} data
   * @memberof WriteInquiryComponent
   */
  public FilterToGroup(fliterData, data) {
    if (fliterData) {
      // 储存fliterData的数组
      var strArr = [];
      // 如果没有包含,
      if (!fliterData.includes(",")) {
        strArr.push(fliterData);
      } else {
        strArr = fliterData.split(",");
      }
      // 循环基金列表，将和filter一样的数组取出来并在未剔除数组中删掉
      for (let item = 0; item < data.length; item++) {
        for (let i = 0; i < strArr.length; i++) {
          // 如果基金列表中包含已剔除的数据
          if (data[item].vcFundCode === strArr[i]) {
            this.deleteList.push(data[item]);
          }
        }
      }

      // 已剔除的数据下标数组
      var dataIndex = [];
      _.forEach(this.deleteList, item => {
        for (var i in data) {
          if (data[i] == item) {
            dataIndex.push(i);
          }
        }
      });

      // 在未剔除数组中删除已选择的数据，倒着删是因为每次删除会让数组长度发生变化。倒着删除则无影响
      _.forEach(dataIndex.reverse(), item => {
        this.withoutDeleteList.splice(item, 1);
      });
    }
  }

  // 转移所有未剔除数据
  public transferAllWithoutData(){
    this.deleteList = this.deleteList.concat(this.withoutDeleteList);
    this.withoutDeleteList = [];
  }

  // 转移所有未剔除数据
  public transferAllDeleteData(){
    this.withoutDeleteList = this.withoutDeleteList.concat(this.deleteList);
    this.deleteList = [];
  }

  // 将未剔除数组转移到剔除数据中
  public transferDataToDeleteList() {
    // 过滤出已选择的数组
    var checkedWithoutDeleteData = _.filter(this.withoutDeleteList, {isChecked: true});
    if (checkedWithoutDeleteData.length === 0) {
      return window["swal"]("提示", "请选择一条数据进行操作", "info");
    }
    // 已选择数据Id数组变量
    var chooseDataFundIdArray = [];
    // 已选择数据数组中下标数组变量
    var chooseDataIndexArray = [];

    // 遍历已经选中的未剔除数组，将每条数据的基金代码存起来。并且找出下标用于删除
    _.forEach(checkedWithoutDeleteData, item => {
      chooseDataFundIdArray.push(item.vcFundCode);
      for (var i in this.withoutDeleteList) {
        if (this.withoutDeleteList[i] == item) {
          chooseDataIndexArray.push(i);
        }
      }
    });

    // 在未剔除数组中删除已选择的数据
    _.forEach(chooseDataIndexArray.reverse(), item => {
      this.withoutDeleteList.splice(item, 1);
    });

    // 填充已剔除数组
    this.deleteList = this.deleteList.concat(checkedWithoutDeleteData);
    // 取消选择
    _.forEach(this.deleteList, item => {
      item.isChecked = false;
    });
    var arr = [];
    // 将新数据推进剔除数组中
    this.deleteList.forEach(item => {
      arr.push(item.vcFundCode);
    })
    this.writeInquiryModalData.vcFundFilter = arr.join(',');
  }

  // 将剔除数组转移到未剔除数据中
  public transferDataToWithoutDeleteList() {
    // 过滤出已选择的数组
    var checkedDeleteData = _.filter(this.deleteList, {isChecked: true});
    if (checkedDeleteData.length === 0) {
      return window["swal"]("提示", "请选择一条数据进行操作", "info");
    }
    // 已选择数据Id数组变量
    var chooseDataFundIdArray = [];
    // 已选择数据数组中下标
    var chooseDataIndexArray = [];

    // 将选择的数据基金代码和下标存起来
    _.forEach(checkedDeleteData, item => {
      chooseDataFundIdArray.push(item.vcFundCode);
      for (var i in this.deleteList) {
        if (this.deleteList[i] == item) {
          chooseDataIndexArray.push(i);
        }
      }
    });

    // 在未剔除数组中删除已选择的数据
    _.forEach(chooseDataIndexArray.reverse(), item => {
      this.deleteList.splice(item, 1);
    });

    // 填充已剔除数组
    this.withoutDeleteList = this.withoutDeleteList.concat(checkedDeleteData);
    // 取消选择
    _.forEach(this.withoutDeleteList, item => {
      item.isChecked = false;
    });

    var arr = [];
    this.deleteList.forEach(item => {
      arr.push(item.vcFundCode);
    });
    this.writeInquiryModalData.vcFundFilter = arr.join(',');
  }

  /**
   * 撤销自动生成的询价列表
   */
  deleteInquiryList() {
    var param = {
      lNewStockNo: this.writeInquiryModalData.vcNewstockId
    }
    return this.WriteInquiryService.deleteInquiryList(param).subscribe(result => {
      if (result) {
        if (result.code === 0) {
          if (result.data.successCount) {
            window["swal"]("提示", result.data.successCount, "info");
          }
        }
      }
    });
  }

  // 校验是否符合资格提交
  validateSave(){
    var isPass = true;
    const $ = window['$'];
    $(".required-input").each((index,item)=> {
      if (item.value === "") {
        window["swal"]("提示", item.placeholder + "不能为空", "info");
        isPass = false;
        return false;
      }
      if (item.id === "enPredictRate" || item.id === "enScaleCoefficient"){
        if(item.value > 100){
          window["swal"]("提示", item.placeholder + "不能大于100", "info");
          isPass = false;
          return false;
        }
      }
    });
    return isPass;
  }

  // 保存
  updateNewStock() {
    if(this.validateSave()){
      this.reSetMoneyAndPercent();
      return this.WriteInquiryService.updateNewStock(this.writeInquiryModalData).subscribe(result => {
        if (result) {
          if (result.code === 0) {
            window["swal"]("提示", "保存成功", "success");
            this.closeModal();
          }
        }
      });
    }
  }

  // 保存并提交
  saveAndSubmit() {
    if(this.validateSave()){
      this.reSetMoneyAndPercent()
      return this.WriteInquiryService.saveAndSubmit(this.writeInquiryModalData).subscribe(result => {
        if (result) {
          if (result.code === 0) {
            window["swal"](`${result.data.result}`,
              `
                      ${result.data.maxAmountStr ? result.data.maxAmountStr + "\n" : ""}
                      ${result.data.reftraceStr ? result.data.reftraceStr + "\n" : ""}
                      ${result.data.fundInfoStr ? result.data.fundInfoStr + "\n" : ""}
                      ${result.data.successCount ? result.data.successCount + "\n" : ""}
                      `,
              "success");
            this.closeModal();
          }
        }
      });
    }
  }
}
